package com.yt.common.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/*
 * @author: chenyu.wang
 * @date: 2020-08-28
 * @description:关于类的操作的工具类
 */
public class ClassUtil {

    private ClassUtil() {
        throw new Error("工具类不允许实例化！");
    }


    /*
     * @description:要获取属性的类
     * @author: chenyu.wang
     * @date: 2020-08-28
     */
    public static Field[] getClassAttribute(Object targetObj) {
        Class<?> objectClass = targetObj.getClass();
        return objectClass.getDeclaredFields();
    }

    public static List<Method> getMethod(Object targetObj, String methodKeyword) {
        List<Method> methodList = new ArrayList<>();
        Class<?> objectClass = targetObj.getClass();
        Field[] field = objectClass.getDeclaredFields();
        for (int i = 0; i < field.length; i++) {
            //获取属性名并组装方法名
            String fieldName = field[i].getName();
            String getMethodName = methodKeyword
                    + fieldName.substring(0, 1).toUpperCase()
                    + fieldName.substring(1);
            try {
                Method method = objectClass.getMethod(getMethodName);
                methodList.add(method);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return methodList;
    }

    public static List<Method> getMethodGet(Object targetObj) {
        return getMethod(targetObj, "get");
    }

    public static List<Method> getMethodSet(Object targetObj) {
        return getMethod(targetObj, "set");
    }
}
